package com.zjc.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjc.common.R;
import com.zjc.pojo.Bulider;
import com.zjc.pojo.DromAdmin;
import com.zjc.pojo.Student;
import com.zjc.service.BuliderService;
import com.zjc.service.DromAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 周佳成
 * @since 2023-09-17
 */
@RestController
@RequestMapping("/api/dromadmin")
public class DromAdminController {
	@Autowired
	DromAdminService dromAdminService;
	@Autowired
	BuliderService buliderService;
	@PostMapping("/login")
	public R<DromAdmin> login(HttpServletRequest httpServletRequest, @RequestBody DromAdmin dromAdmin){
		String password = dromAdmin.getSgPassword();

		LambdaQueryWrapper<DromAdmin> lambdaQueryWrapper = new LambdaQueryWrapper<>();

		lambdaQueryWrapper.eq(DromAdmin::getSgId,dromAdmin.getSgId());

		DromAdmin drom = dromAdminService.getOne(lambdaQueryWrapper);

		if(drom == null){
			return R.error("用户名不存在!");
		}
		else{
			String pw = drom.getSgPassword();
			if(!pw.equals(password)){
				return R.error("密码错误!");
			}
			else{
				httpServletRequest.getSession().setAttribute("stu",drom.getSgId());
				return R.success(drom);
			}
		}
	}

	@GetMapping("/find")
	public R<Page> GetSgPage(int pageNum, int pageSize, String search){
		QueryWrapper<DromAdmin> wrapper = new QueryWrapper<>();

		wrapper.like("sg_name",search);
		wrapper.orderByAsc("sg_id");
		Page<DromAdmin> page1 = new Page<>(pageNum,pageSize);
		dromAdminService.page(page1,wrapper);
		return R.success(page1);
	}
	@PutMapping("/update")
	public R<String> changeStu(@RequestBody DromAdmin dromAdmin){
		Integer ldid = dromAdmin.getLdId();
		if(!dromAdminService.isExistsLd(ldid)){
			return R.error("楼栋号不存在！");
		}
		boolean rows=dromAdminService.updateById(dromAdmin);
		System.out.println(rows);
		return R.success("修改成功");
	}
	@PostMapping("/add")
	public R<String> addStu(@RequestBody DromAdmin dromAdmin){
		Integer sgid = dromAdmin.getSgId();
		Integer ldid = dromAdmin.getLdId();

		if(dromAdminService.isExistsSg(sgid)){
			return R.error("宿管已经存在！！请勿重复添加");
		}

		if(!dromAdminService.isExistsLd(ldid)) {
			return R.error("楼栋号不存在！");
		}

		dromAdminService.save(dromAdmin);
		return R.success("添加成功");
	}
	@DeleteMapping("/delete/{sgId}")
	public R<String> deleteSg(@PathVariable Integer sgId){
		System.out.println(sgId);
		int rows=dromAdminService.deleteSg(sgId);
		if(rows!=0){
			return R.success("删除成功");
		}
		else{
			return R.error("删除失败");
		}
	}
}

